<!-- 表单引擎组件 -->
<template>
  <el-form class="form_engine_component"
    ref="formEngineRef"
    :model="formData"
    :label-width="schema.labelWidth || '100px'"
    :label-position="schema.labelPosition || 'right'"
    :inline="schema.inline || false"
    :size="schema.size || 'default'"
    :rules="schema.rules"
    @submit.prevent="handleSubmit">
    <template v-for="item in visibleItems" :key="item.field">
      <FormItem :item="item" :fieldWidth="schema.fieldWidth" :formData="formData" @change="handleFiledChange" />
    </template>
    <el-form-item>
      <slot name="footer" :submit="submit" :reset="resetForm">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </slot>
    </el-form-item>
  </el-form>
</template>
<script setup>
  import { ref, computed, nextTick } from 'vue';
  import FormItem from './components/FormItem.vue';

  const { schema, initValues } = defineProps({
    schema: {
      type: Object,
      default: () => ({})
    },
    initValues: {
      type: Object,
      default: () => ({})
    }
  })
  const formEngineRef = ref(null)

  // 初始化表单数据
  const formData = ref({ ...initValues })

  const visibleItems = computed(() => {
    console.log("🚀 ~ visibleItems:", schema.items)
    return schema.items.filter(item => {
      
      if (typeof item.hidden === 'function') {
        return !item.hidden(formData.value)
      }
      return !item.hidden
    });
  })


  const emit = defineEmits(['submit', 'change'])
  // 表单项change事件
  const handleFiledChange = (field, value) => {
    emit('change', field, value)
  }

  // 表单提交
  const handleSubmit = async () => {
    await formEngineRef.value.validate()
    emit('submit', formData.value)
  }

  // 表单重置
  const resetForm = () => {
    formData.value = { ...initValues }
    nextTick(() => { // 清空校验
      formEngineRef.value.resetFields()
    })
  }

  // 暴露方法
  defineExpose({
    handleSubmit,
    resetForm
  })




</script>
<style scoped lang="scss">
  .form_engin_page {
    width: 100%;
    height: 100%;
  }
</style>